// pages/operate/operate.js
import * as echarts from '../../ec-canvas/echarts';
const app = getApp();
let chart = { setOption: function () { } };
var option = {
  tooltip: {
    formatter: '{a} \n {b} : {c}℃'
  },
  grid: {
    width: "100%",
    height: "100%"
  },
  toolbox: {

  },
  grid: {
    top: "0px",
    left: "0px",
    right: "0px",
    bottom: "0px"
  },
  series: [{
    radius: '100%',
    pointer: {
      show: false,
      length: '20%'
    },
    title: {
      show: false
    },
    splitLine: {
      show: false,
      length: 10,
      lineStyle: {
        color: 'white',
        width: 3
      }

    },

    //刻度样式
    axisTick: {
      show: true,
    },
    //刻度标签。
    axisLabel: {
      show: false,
    },

    axisLine: {
      show: true,

      lineStyle: {
        width: 20,
        color: [
          [0.1, '#ffffff'],
          [0.8, '#ffffff'],
          [1, '#ffffff']
        ],
        opacity: 0.1
      }
    },
    name: '设备温度',
    type: 'gauge',
    detail: {
      show: false,
      formatter: '{value}℃'
    },
    data: [{
      value: 50,
      name: '温度'
    }]
  },
  {
    name: '外侧线条',
    radius: '100%',
    type: 'gauge',
    pointer: {
      show: false,
      length: '20%'
    },

    splitLine: {
      show: false
    },
    title: {
      show: false
    },
    //刻度样式
    axisTick: {
      show: false,
    },
    //刻度标签。
    axisLabel: {
      show: false,
    },
    axisLine: { // 坐标轴线
      show: true,
      lineStyle: { // 属性lineStyle控制线条样式
        width: 3,
        color: [
          [0, '#ffffff']
        ]
      }

    },
    detail: {
      show: false,
      offsetCenter: [0, '0%'],
      formatter: (value) => {
        var tmp = value * 0.16 + 16
        return tmp.toFixed(0) + '℃'
      },
      textStyle: {
        fontSize: '60'
      }

    },
    data: [{
      value: 0,
      name: '温度'
    }],
  }
  ]
}
// 2、进行初始化数据
function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);
  var x = parseInt(width) / 2;
  var y = parseInt(height) / 2;
  var minAngle = 0;
  var maxAngle = 180;


  chart.setOption(option);
  // chart._zr.on('mousedown', function (event) {
  //   changeValue(event, x, y);
  //   chart._zr.on('touchmove', changeValue(event, x, y));
  // });
  // chart._zr.on('mouseup', function (event) {
  //   chart._zr.off('touchmove', changeValue(event, x, y));
  // });
  return chart;
}

function changeValue(event, x, y) {
  console.log(event, x, y);
  var minAngle = 0;
  var maxAngle = 180;
  var maxValue = 100;
  var dataRatio = maxValue / maxAngle;
  var x2 = event.offsetX;
  var y2 = event.offsetY;
  // 当前点击位置的角度.
  var currentAngle = Math.atan2(y - y2, x - x2) * 180 / Math.PI;
  // 边界处理
  if (currentAngle < minAngle || currentAngle > maxAngle) {
    let _angle = Math.abs(currentAngle);
    if (_angle > 90) {
      currentAngle = maxAngle;
    } else {
      currentAngle = minAngle;
    }
  }
  // 转换回数据值, 这里就是实际的值, 默认保留2位小数.
  let value = (currentAngle * dataRatio).toFixed(1);
  option.series[1].data[0].value = value;
  option.series[1].axisLine.lineStyle.color = [
    [value / 100, '#ffffff']
  ];
  chart.setOption(option);
}

Page({

  /**
   * 页面的初始数据
   * 
   */
  data: {
    ec: {
      onInit: initChart // 3、将数据放入到里面
    },
    btn_list: [{
      id: 1,
      name: '制冷',
      icon: 'set_icon_cool_def.svg',
      activeIcon: 'set_icon_cool_pre.svg',
      active: true
    }, {
      id: 0,
      name: '制热',
      icon: 'set_icon_hot_def.svg',
      activeIcon: 'set_icon_hot_pre.svg',
      active: false

    }, {
      id: 3,
      name: '风速',
      icon: 'set_icon_wind1.svg',
      activeIcon: 'set_icon_wind_small_pre.svg',
      active: true

    }, {
      id: 2,
      name: '自动',
      icon: 'set_icon_auto_def.svg',
      activeIcon: 'set_icon_auto_pre.svg',
      active: false
    }],
    deviceInfo: { Mode_heat: 0, Mode_fan: 0 },
    colorStatus: 0,
  },

  changeStatus(e) {
    console.log(e);
    var index = null
    var list = this.data.btn_list
    var id = e.currentTarget.dataset.id
    var info = this.data.deviceInfo
    if (id !== 3 && this.data.deviceInfo.Runningif == 1) {
      // list.forEach((item, i) => {
      //   if (item.id !== 3) {
      //     item.active = false
      //   }
      //   if (item.id == id) {
      //     item.active = true
      //   }
      // })
      // this.setData({
      //   btn_list: list,
      //   colorStatus: id, // 模式状态
      //   ["deviceInfo.Mode_heat"]: id
      // })
      info.Mode_heat = id
      this.publish(info)
    }

    else if (id == 3 && this.data.deviceInfo.Runningif == 1) {
      let windStatus = this.data.deviceInfo.Mode_fan
      if (windStatus == 2) {
        info.Mode_fan = 0
        this.publish(info)
        // list[2].name = '低'
        // this.setData({
        //   ['deviceInfo.Mode_fan']: 0,
        //   btn_list: list,
        // })
      } else {
        var z = windStatus + 1
        info.Mode_fan = z
        this.publish(info)
        // if (z == 1) {
        //   list[2].name = '中'
        // } else if (z == 2) {
        //   list[2].name = '强'
        // }
        // this.setData({
        //   btn_list: list,
        //   ['deviceInfo.Mode_fan']: z
        // })
      }

    }
  },
  handleClose() {
    var status = this.data.deviceInfo.Runningif
    var info = this.data.deviceInfo
    var list = this.data.btn_list
    if (status == 1) {
      status = 0
      // list.forEach((item, i) => {
      //   item.active = false
      // })
      // this.setData({
      //   colorStatus: -1,
      //   btn_list: list
      // })
    } else {
      status = 1
      // var activeIndex = this.data.deviceInfo.Mode_heat
      // list.forEach(item => {
      //   if (item.id == activeIndex || item.id == 3) {
      //     item.active = true
      //   } else if (item.id !== 3) {
      //     item.active = false
      //   }
      // })
      // this.setData({
      //   colorStatus: activeIndex,
      //   btn_list: list
      // })
    }
    // this.setData({
    //   ["deviceInfo.Runningif"]: status,
    // })
    info.Runningif = status
    this.publish(info)


    // } else {
    //   var index = this.data.oldStatus
    //   var list = this.data.btn_list
    //   list[index].active = true
    //   this.setData({
    //     btn_list: list,
    //     colorStatus: index,
    //     windStatus: this.data.oldWindStatus
    //   })
    // }
  },
  addTemp() {
    var value = option.series[1].data[0].value
    let info = this.data.deviceInfo
    if (value < 100) {
      // option.series[1].data[0].value = value + 25 / 4;
      // option.series[1].axisLine.lineStyle.color = [
      //   [(value + 25 / 4) / 100, '#ffffff']
      // ];
      // chart.setOption(option);
      info.Temp_set = info.Temp_set + 1
      // this.setData({
      //   deviceInfo: info
      // })
      this.publish(info)
    }
  },
  reduceTemp() {
    var value = option.series[1].data[0].value
    let info = this.data.deviceInfo
    if (value > 0) {
      // option.series[1].data[0].value = value - 25 / 4;
      // option.series[1].axisLine.lineStyle.color = [
      //   [(value - 25 / 4) / 100, '#ffffff']
      // ];
      // chart.setOption(option);
      info.Temp_set = info.Temp_set - 1
      // this.setData({
      //   deviceInfo: info
      // })
      this.publish(info)
    }
  },
  goback() {
    wx.navigateBack({
      delta: 1
    })

  },
  setDeviceInfo(deviceInfo) {
    var self = this
    var value = (deviceInfo.Temp_set - 16) * 25 / 4
    option.series[1].data[0].value = value
    option.series[1].axisLine.lineStyle.color = [
      [(value) / 100, '#ffffff']
    ];
    chart.setOption(option)
    var list = this.data.btn_list
    list.forEach(item => {
      if (item.id == deviceInfo.Mode_heat) {
        item.active = true
      } else if (item.id !== 3) {
        item.active = false
      }
    })
    this.setData({
      deviceInfo,
      btn_list: list,
      colorStatus: deviceInfo.Mode_heat
    })
  },

  // 发布修改状态
  publish(deviceInfo) {
    let msg = {
      Mode_fan: deviceInfo.Mode_fan,
      Mode_heat: deviceInfo.Mode_heat,
      Runningif: deviceInfo.Runningif,
      Temp_set: deviceInfo.Temp_set,
      mac: deviceInfo.mac
    }
    app.client.publish(`/sirui/iot/define/5/MESHID:${deviceInfo.mesh_id}/cmdControl/json`, JSON.stringify(msg))
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this
    var deviceInfo = JSON.parse(options.deviceInfo)
    console.log(deviceInfo);
    self.setDeviceInfo(deviceInfo)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var self = this
    app.client.on('message', function (topic, message, packet) {
      // message is Buffer
      let mess = message.toString()
      let message1 = JSON.stringify(mess)
      var msg = JSON.parse(JSON.parse(message1))
      if(topic.includes('will')){
        self.setData({
          ['deviceInfo.status'] : 0
        })
      }else{
        if (msg.MAC == self.data.deviceInfo.mac) {
          var deviceMsg = self.data.deviceInfo
          deviceMsg.name = msg.NAME
          deviceMsg.Temp_set = msg.Temp_set
          deviceMsg.Mode_fan = msg.Mode_fan
          deviceMsg.Mode_heat = msg.Mode_heat
          deviceMsg.Temp_real = msg.Temp_real
          deviceMsg.Runningif = msg.Runningif
          deviceMsg.status = msg.Status
          self.setDeviceInfo(deviceMsg)
        }
      }
     
    })
  },
  // 修改设备信息
  handleEdit(){
    wx.navigateTo({
      // url: '/pages/blueDevices/blueDevices?flag=false'
      url: '/pages/option/option?deviceInfo='  + JSON.stringify(this.data.deviceInfo)
    })
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})